import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

// 定义缓存项接口
interface CacheItem<T> {
    data: T
    timestamp: number
    expirationTime: number
}

// 定义页面缓存状态
interface PageCacheState {
    cachedPages: Record<string, CacheItem<any>>
}

export const usePageCacheStore = defineStore('pageCache', {
    state: (): PageCacheState => ({
        cachedPages: {}
    }),

    getters: {
        // 获取特定页面的缓存
        getPageCache: (state) => (pageKey: string) => {
            return state.cachedPages[pageKey]
        },

        // 检查特定页面是否有有效缓存
        hasValidPageCache: (state) => (pageKey: string, currentTime = Date.now()) => {
            const cacheItem = state.cachedPages[pageKey]
            if (!cacheItem) return false

            return currentTime - cacheItem.timestamp <= cacheItem.expirationTime
        }
    },

    actions: {
        // 缓存页面数据
        cachePageData<T>(pageKey: string, data: T, expirationTime: number) {
            this.cachedPages[pageKey] = {
                data,
                timestamp: Date.now(),
                expirationTime
            }
        },

        // 获取页面缓存数据，如果已过期则返回null
        getPageData<T>(pageKey: string): T | null {
            const cacheItem = this.cachedPages[pageKey]
            if (!cacheItem) return null

            const isExpired = Date.now() - cacheItem.timestamp > cacheItem.expirationTime
            if (isExpired) {
                this.clearPageCache(pageKey)
                return null
            }

            return cacheItem.data
        },

        // 从API获取数据并缓存
        async fetchAndCachePageData<T>(
            pageKey: string,
            fetchFunction: () => Promise<T>,
            expirationTime: number = 60 * 1000
        ): Promise<T> {
            const cachedData = this.getPageData<T>(pageKey)
            if (cachedData) return cachedData

            const freshData = await fetchFunction()
            this.cachePageData(pageKey, freshData, expirationTime)
            return freshData
        },

        // 刷新页面缓存
        async refreshPageCache<T>(
            pageKey: string,
            fetchFunction: () => Promise<T>,
            expirationTime: number = 60 * 1000
        ): Promise<T> {
            this.clearPageCache(pageKey)
            const freshData = await fetchFunction()
            this.cachePageData(pageKey, freshData, expirationTime)
            return freshData
        },

        // 清除特定页面缓存
        clearPageCache(pageKey: string) {
            delete this.cachedPages[pageKey]
        },

        // 清除所有页面缓存
        clearAllPageCache() {
            this.cachedPages = {}
        }
    }
})
